<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 短信操作类
 * @package  	htdocs
 * @subpackage  module
 * @author  	allen.qiang
 * @version 	1.0
 */

quanli_require('module/base/common/quanliHttp.class.php');

class smsHandler {

    private $dbca;

    public function __construct( &$dbca ) {
        $this->dbca = $dbca;
    }


    /**
     * 生成短信验证码
     * @param int $num
     * @return string
     */
    public function createSmsCode( $num = 6 ) {

        //验证码字符数组
        $n_array = range(0, 9);

        //随机生成$num位验证码字符
        $code_array = array_rand($n_array, $num);

        //重新排序验证码字符数组
        shuffle( $code_array );

        //生成验证码
        $code = implode('', $code_array);

        return $code;

    }


    /**
     * 发送短信
     * @param int $mobile 手机号
     * @param string $sms_conent 短信内容
     * @return array
     */
    public function sendSMS( $mobile, $sms_conent ) {

        if (!isset($mobile, $sms_conent) || empty($mobile) || empty($sms_conent)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //生成短信内容
        $companyUser = 'hb_lppz';
        $companyPwd = 'smgs2001';
        $sms_conent = iconv('utf-8', 'gbk', $sms_conent);
        $sms_str = 'http://hb.ums86.com:8899/sms/Api/Send.do?SpCode=207849&LoginName=' . $companyUser . '&Password=' . $companyPwd . '&MessageContent=' . $sms_conent . '&UserNumber=' . $mobile . '&SerialNumber=&ScheduleTime=&f=1';

        //发送短信
        $rpc_http = new quanliHttp();
        $output = $rpc_http->get($sms_str);
        //接收短信
        if (isset($output['code'],$output['data']) && $output['code'] == 200 && substr($output['data'],0,8) == 'result=0') {
        	return array( 'code' => 200, 'message' => '短信发送成功' );
        } else {
        	return array( 'code' => 404, 'message' => '短信发放失败' );
        }
    }

/*--------------------------------------------------------------------------------以下为企业编码207850的账号---------------------------------------------------------*/
    /**
     * 点对点短信(207850账号的)
     * @param int $mobile 手机号
     * @param string $sms_conent 短信内容
     * @return array
     */
    public function sendActivitySMS( $mobile, $sms_conent ) {

        if (!isset($mobile, $sms_conent) || empty($mobile) || empty($sms_conent)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //生成短信内容
        $companyUser = 'hb_lpdz';
        $companyPwd = 'smgs2002';
        $sms_conent = iconv('utf-8', 'gbk', $sms_conent);
        $sms_str = 'http://hb.ums86.com:8899/sms/Api/Send.do?SpCode=207850&LoginName=' . $companyUser . '&Password=' . $companyPwd . '&MessageContent=' . $sms_conent . '&UserNumber=' . $mobile . '&SerialNumber=&ScheduleTime=&f=1';

        //发送短信
        $rpc_http = new quanliHttp();
        $output = $rpc_http->get($sms_str);

        //接收短信
        if (isset($output['code'],$output['data']) && $output['code'] == 200 && substr($output['data'],0,8) == 'result=0') {
            return array( 'code' => 200, 'message' => '短信发送成功' );
        } else {
            return array( 'code' => 404, 'message' => '短信发放失败' );
        }
    }

    /**
     * 活动群发短信
     * @param array $mobile_array 用户手机号数组
     * @param string $sms_conent 短信内容
     * @return array
     */
    public function groupSendSMS($mobile_array, $sms_conent){
        if (!isset($mobile_array, $sms_conent) || !is_array($mobile_array) || empty($sms_conent)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //分割数组
        $userName_arr = array_chunk($mobile_array,1000);

        foreach($userName_arr as $value){
            //数组转化为字符串
            $userName_str = implode(',',$value);
            //批量发送
            $this->sendActivitySMS( $userName_str, $sms_conent );
        }
    }

    /**
     * 查询上行短信
     * @return array
     */
    public function receiveSMS($messageID = null) {

        //生成url内容
        $companyUser = 'hb_lpdz';
        $companyPwd = 'smgs2002';

        //查询消息读取记录表最后一条数据的短信ID
//        $messageID_Obj = $this->dbca->stmt_query('SELECT smsID FROM log_read_sms ORDER BY logID DESC LIMIT 0,1 ');
//        if(empty($messageID)){
//            $messageID = $messageID_Obj[0]->smsID;
//        }

        if($messageID > 0){
            $sms_str = 'http://hb.ums86.com:8899/sms/Api/reply.do?SpCode=207850&LoginName=' . $companyUser . '&Password=' . $companyPwd .'&id=' . $messageID ;
        }else{
            $sms_str = 'http://hb.ums86.com:8899/sms/Api/reply.do?SpCode=207850&LoginName=' . $companyUser . '&Password=' . $companyPwd ;
        }
        //查询上行短信
        $rpc_http = new quanliHttp();
        $output = $rpc_http->get($sms_str);
        //接收短信
        if (isset($output['code'],$output['data']) && $output['code'] == 200 && substr($output['data'],0,8) == 'result=0') {
            $str = $output['data'];
            $result_arr = explode('&',$str);
            $find = array("replys=[","]");
            if(isset($result_arr[3])&&!empty($result_arr[3])){
                $result_content = str_replace($find,"",$result_arr[3]);
                $result = json_decode($result_content,true);

                //更新查询记录表
                $messageID = $result['id'];   //上次最后查询到的短信ID
                $now_time = date('Y-m-d H:i:s');   //当前时间

                $log_read_sms = new entity('log_read_sms');
                $log_read_sms->timeStamp        = $now_time;
                $log_read_sms->creator          ='system';
                $log_read_sms->createTime       =$now_time;
                $log_read_sms->smsID            =$messageID;

                //保存
                $this->dbca->save($log_read_sms);

                //退订
//            if($result['content'] == 'TD'){
                if($result['content'] == '回复短信，退订'){

                    quanli_require('module/base/userHandler.class.php');

                    $userHandler = new userHandler($this->dbca);
                    $createBlack_result = $userHandler ->creatBlackUser(array('mobile'=>$result['mdn']));
                    if($createBlack_result['code'] == 200){
                        $this->sendActivitySMS($result['mdn'],'退订成功！给你造成的困扰我们深表歉意！');
                    }
                }

            }
            return array( 'code' => 200, 'message' => '查询成功','data'=> $output['data']);
        } else {
            return array( 'code' => 404, 'message' => '查询失败' );
        }
    }


    /**
     * 短信发送回执
     * @return array
     */
    public function reportSMS() {

        //生成短信内容
        $companyUser = 'hb_lpdz';
        $companyPwd = 'smgs2002';

        $sms_str = 'http://hb.ums86.com:8899/sms/Api/report.do?SpCode=207850&LoginName=' . $companyUser . '&Password=' . $companyPwd ;
        error_log(print_r($sms_str,true));
        //发送短信
        $rpc_http = new quanliHttp();
        $output = $rpc_http->get($sms_str);

error_log(print_r($output,true));
        //接收短信
        if (isset($output['code'],$output['data']) && $output['code'] == 200 && substr($output['data'],0,8) == 'result=0') {
            return array( 'code' => 200, 'message' => '短信发送成功' );
        } else {
            return array( 'code' => 404, 'message' => '短信发放失败' );
        }
    }


    //转化查询短信返回字符串
    public function str_arr ($str,$sp,$kv)
    {
        $arr = str_replace(array($kv,$sp),array('"=>"','","'),'array("'.$str.'")');
        eval("\$arr"." = $arr;");
        return $arr;
    }

}